package com.spring.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.spring.gowhere.R;
import com.spring.httputils.PayResult;
import com.spring.httputils.RequestParams;
import com.spring.httputils.RestClient;
import com.spring.httputils.SignUtils;
import com.spring.httputils.TextHttpResponseHandler;
import com.spring.tool.App;

import org.apache.http.Header;
import org.json.JSONObject;
import org.json.alipay.JSONException;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class PayZFBActivity extends BaseActivity {
    private TextView product_price,product_subject,product_boy;
    // 商户PID
    public static final String PARTNER = "2088221949871704";
    // 商户收款账号
    public static final String SELLER = "2088221949871704";
    // 商户私钥，pkcs8格式
    public static final String RSA_PRIVATE = App.Private;
    // 支付宝公钥
    public static final String RSA_PUBLIC = App.Public;
    private static final int SDK_PAY_FLAG = 1;
    private String pice,CustSn,succes;
    private String username, logintype,TransStatus;;
    RestClient restClient = null;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {

                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    //接口2
                    SendHttpPay sendhttp = new SendHttpPay(
                            App.getInstance().url
                                    + "/AlipayTransAccount",TransStatus,resultStatus
                    );
                    sendhttp.run();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {


                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, " ")) {
                            Toast.makeText(PayZFBActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(PayZFBActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                            TransStatus="0";
                        }

                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pay_main);
        Intent intent = getIntent();
        pice =  intent.getStringExtra("pice") ;
        CustSn =  intent.getStringExtra("CustSn") ;
        product_price = (TextView) findViewById(R.id.product_price);
        product_subject=(TextView)findViewById(R.id.product_subject);
        product_boy=(TextView)findViewById(R.id.product_boy);
        product_subject.setText("校园卡充值");
        product_boy.setText("校园卡充值");
        product_price.setText(pice);
        SharedPreferences userInfo = this.getSharedPreferences(
                "user_info", 0);
        username = userInfo.getString("username", "");
        logintype = userInfo.getString("logintype", "");
        restClient = new RestClient(this);
    }

    /**
     * call alipay sdk pay. 调用SDK支付
     */
    public void pay(View v) {
        if (TextUtils.isEmpty(PARTNER) || TextUtils.isEmpty(RSA_PRIVATE) || TextUtils.isEmpty(SELLER)) {
            new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置PARTNER | RSA_PRIVATE| SELLER")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialoginterface, int i) {
                            //
                            finish();
                        }
                    }).show();
            return;
        }
        String orderInfo = getOrderInfo(product_subject.getText().toString(),product_boy.getText().toString() , product_price.getText().toString());
        Log.i("TAG","orderInfo:"+orderInfo);
        /**
         * 特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中！
         */
        String sign = sign(orderInfo);
        try {
            /**
             * 仅需对sign 做URL编码
             */
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        /**
         * 完整的符合支付宝参数规范的订单信息
         */
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(PayZFBActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * get the sdk version. 获取SDK版本号
     */
    public void getSDKVersion() {
        PayTask payTask = new PayTask(this);
        String version = payTask.getVersion();
        Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
    }


    /**
     * create the order info. 创建订单信息
     */
    private String getOrderInfo(String subject, String body, String price) {

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + PARTNER + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + CustSn + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + subject + "\"";

        // 商品详情
        orderInfo += "&body=" + "\"" + body + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + price + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + "http://120.237.110.50:8072/WebService.asmx/AlipayTransAccountFinish" + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;
    }


    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content 待签名订单信息
     */
    private String sign(String content) {
        return SignUtils.sign(content, RSA_PRIVATE);
    }

    /**
     * get the sign type we use. 获取签名方式
     */
    private String getSignType() {
        return "sign_type=\"RSA\"";
    }
    class SendHttpPay implements Runnable {

        String url;
        String TransStatu;
        String fig;
        SendHttpPay(String url,String TransStatus,String fig) {
            this.url = url;
            this.TransStatu = TransStatus;
            this.fig = fig;
        }

        @Override
        public void run() {
            RequestParams requestparams = new RequestParams(url, "POST");
            requestparams.put("LoginAccount", username);
            requestparams.put("LoginType", logintype);
            requestparams.put("CustSn",CustSn);
            requestparams.put("AliPayTransNo","");
            if (fig.equals("9000")){
                requestparams.put("TransStatus","1");
            }else {
                requestparams.put("TransStatus","0");
            }

            requestparams.put("Notes","");
            requestparams.put("TransMoney",product_price.getText().toString());
            TextHttpResponseHandler textHttpResponseHandler = new TextHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers,
                                      String responseString) {
                    // TODO Auto-generated method stub
                    Log.e("TAG", "responseString1122" + responseString);
                    try {
                        Analysis(responseString);
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      String responseString, Throwable throwable) {
                    // TODO Auto-generated method stub
                    Log.i("TAG", "responseString22" + responseString);

                }
            };
            try {
                restClient.post(url, requestparams, textHttpResponseHandler);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        /**
         * json数据解析
         *
         * @param strResult
         * @throws JSONException
         */
        private void Analysis(String strResult) throws JSONException {
            /**
             * 这里需要分析服务器回传的json格式数据，
             */
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(strResult);
            } catch (org.json.JSONException e) {
                e.printStackTrace();
            }
            try {
                String returnMsg = jsonObject.getString("returnMsg");

                if (returnMsg == null || "".equals(returnMsg)) {
                    // TODO Auto-generated method stub
                    succes="成功";

                } else {
                    succes="失败";

                }

                new AlertDialog.Builder(PayZFBActivity.this).setTitle("系统提示")//设置对话框标题

                        .setMessage("充值"+succes)//设置显示的内容

                        .setNegativeButton("确定",new DialogInterface.OnClickListener() {//添加确定按钮

                            @Override

                            public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                               startActivity(new Intent(PayZFBActivity.this,MainActivity.class));
                                finish();
                                // TODO Auto-generated method stub

                            }

                        }).show();//在按键响应事件中显示此对话框
            } catch (org.json.JSONException e) {
                e.printStackTrace();
            }
        }

    }
}
